package com.lis.scf.service;


//import com.lis.scf.common.dto.RegisterDTO;
import com.lis.scf.common.dto.ResponseDTO;
import com.lis.scf.entity.Company;
import com.lis.scf.entity.EnterpriseRegistration;
import com.lis.scf.common.dto.UserRegisterDTO;
import com.lis.scf.entity.Company;
import com.lis.scf.entity.Role;
import com.lis.scf.entity.User;
import com.lis.scf.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * 企业注册服务
 * 处理物流企业和融资客户的注册流程
 */
@Service
@RequiredArgsConstructor
public class RegistrationService {

    private final CompanyRepository companyRepository;
    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final EnterpriseRegistrationRepository registrationRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 企业自助注册
     */
    @Transactional
    public void register(UserRegisterDTO dto) {

        // 检查用户名是否已存在
//        if (userRepository.existsByUsername(dto.getUsername())) {
//            throw new RuntimeException("用户名已存在");
//        }
//        // 1. 验证信用代码唯一性
//        if (companyRepository.existsByUnifiedCreditCode(dto.getUnifiedCreditCode())) {
//            throw new RuntimeException("统一社会信用代码已注册");
//        }

        // 2. 创建企业信息
        Company company = new Company();
        company.setCompanyName(dto.getCompanyName());
        company.setUnifiedCreditCode(dto.getUnifiedCreditCode());
        company.setCompanyType(dto.getCompanyType());
//        company.setCompanyType(Company.CompanyType.valueOf(dto.getCompanyType()));
        company = companyRepository.save(company);

        // 3. 创建管理员用户
        User admin = new User();
        admin.setUsername(dto.getUsername());
        admin.setPassword(passwordEncoder.encode(dto.getPassword()));
        admin.setMobileNumber(dto.getMobileNumber());
        admin.setRealName(dto.getRealName());
        admin.setCompany(company);

        // 4. 分配默认角色
        Set<Role> roles = new HashSet<>();
        String defaultRole = "企业操作岗";
        Optional<Role> roleOpt = roleRepository.findByRoleNameAndCompanyType(
                defaultRole, company.getCompanyType()
        );
        roleOpt.ifPresent(roles::add);
        admin.setRoles(roles);
        userRepository.save(admin);

        // 5. 记录注册流程
        EnterpriseRegistration registration = new EnterpriseRegistration();
        registration.setCompany(company);
        registration.setRegistrationStep("自助注册");
        registration.setEntryCondition("无");
        registration.setAdminMobile(dto.getMobileNumber());
//        registration.setSmsVerificationCode(dto.getSmsCode());
        registration.setRegistrationStatus(EnterpriseRegistration.RegistrationStatus.申请中);
        registration.setStepCompleteTime(LocalDateTime.now());
        registrationRepository.save(registration);

    }

    /**
     * 完善企业信息
     */
    @Transactional
    public void completeEnterpriseInfo(Long companyId, String address, String scope, String assetScale) {
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new RuntimeException("企业不存在"));

        company.setBusinessAddress(address);
        company.setBusinessScope(scope);
        // 转换资产规模为BigDecimal
        try {
            company.setAssetScale(new java.math.BigDecimal(assetScale));
        } catch (NumberFormatException e) {
            throw new RuntimeException("资产规模格式错误");
        }
        companyRepository.save(company);

        // 更新注册流程状态
//        EnterpriseRegistration registration = registrationRepository.findByCompany_CompanyId(companyId)
//                .orElseThrow(() -> new RuntimeException("注册记录不存在"));
//        registration.setRegistrationStep("信息完善");
//        registration.setEntryCondition("客户自主注册完成");
//        registration.setStepCompleteTime(LocalDateTime.now());
//        registrationRepository.save(registration);
    }
}
